package com.wxm.common.file.core.util;

import com.wxm.common.file.core.exception.FileException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * <p>
 *      文件工具类
 * </p>
 *
 * @author: wxm
 * @Date: 2022/01/21
 */
public class FileUtils {
    private FileUtils(){}

    /**
     * 获取流中的数据
     * @param inputStream inputStream
     * @param closeTag 是否关闭inputStream
     * @return byte[]
     */
    public static byte[] getBytes(InputStream inputStream,Boolean closeTag){
        byte[] buffer = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            if (closeTag) {
                inputStream.close();
            }
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e){
            FileException.error("读取文件失败");
        }
        return buffer;
    }

    /**
     * 路径转File
     * @param filePath 文件路径
     */
    public static File urlToFile(String filePath) {
        File file = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL imageUrl = new URL(filePath);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            try (
                    InputStream inputStream =  conn.getInputStream();
            ){
                byte[] bytes = FileUtils.getBytes(inputStream,true);
                file = File.createTempFile("file", filePath.substring(filePath.lastIndexOf(".")));
                fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream stream = new BufferedOutputStream(fileOutputStream);
                stream.write(bytes);
            } catch (FileNotFoundException e) {
                FileException.error("文件创建失败 路径：" + filePath);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                fileOutputStream.close();
            }
        }catch (IOException e){
            FileException.error("文件创建失败 路径：" + filePath);
        }
        return file;
    }

    /**
     * 文件转Byte数组
     * @param file 文件
     * @return byte[]
     */
    public static byte[] getBytes(File file){
        try (
                //创建输入流
                FileInputStream fis = new FileInputStream(file);
                //新的 byte 数组输出流，缓冲区容量1024byte
                ByteArrayOutputStream bos = new ByteArrayOutputStream(1024)
        ){
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            //改变为byte[]
            return bos.toByteArray();
        }catch (Exception e){
            FileException.error("读取文件失败");
        }
        return null;
    }

    /**
     * 创建空文件
     * @param path 路径
     * @return File
     */
    public static File createNewFile(String path){
        File localFile = new File(path);
        try {
            //先拆分判断是否需要先创建文件夹
            String substring = path.substring(0, path.lastIndexOf("/"));
            if (StringUtils.isNotBlank(substring)){
                File file = new File(substring);
                file.mkdirs();
            }
            if (!localFile.exists()) {
                boolean newFile = localFile.createNewFile();
            }
        }catch (Exception e){
            FileException.error("文件创建失败 路径：" + path);
        }
        return localFile;
    }

    /**
     * 拷贝InputStream流
     * @param inputStream InputStream
     * @return ByteArrayOutputStream
     */
    public static ByteArrayOutputStream cloneInputStream(InputStream inputStream) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            return bos;
        } catch (IOException e) {
            FileException.error("InputStream流拷贝失败：" + e.getMessage());
            return null;
        }
    }
}
